<template>
  <div class="history">
    <!-- <el-button class="database" type="text" @click="dialogVisible = true; ashow = false">数据库脚本导出</el-button> -->
    <el-dialog title="数据库脚本导出" :visible.sync="dialogVisible" width="30%" v-loading="dialog">
    <div class="demo-input-suffix">
      <el-row :gutter="5">
        <el-col :span="5">
          <span class="span">文件名：</span>
        </el-col>
        <el-col :span="19">
          <el-input placeholder="请输入文件名称" prefix-icon="el-icon-search" v-model="filename"> </el-input>
        </el-col>
      </el-row>
    </div>
    <span slot="footer" class="dialog-footer">
    <el-button @click="dialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="outdatabase">导 出</el-button>
    <a v-show="ashow" href="url">下载</a>
    </span>
    </el-dialog>
    <el-tabs v-model="activeName"  v-loading="loading">
      <!-- 用户管理展示 -->
      <el-tab-pane label="山体数据" name="first">
        <!-- 卡片区域视图 -->
        <el-card>
          <el-row :gutter="20">
            <el-col :span="10">
              <!-- 搜索与添加区域 -->
              <el-input
                placeholder="请输入内容"
                v-model="queryInfo.query"
                clearable
              >
                <el-button
                  slot="append"
                  icon="el-icon-search"
                ></el-button>
              </el-input>
            </el-col>
            <!-- 选择时间范围 -->
            <el-col :span="10">
              <el-date-picker
                v-model="time"
                type="datetimerange"
                value-format="yyyy-MM-dd HH:mm:ss"
                :picker-options="pickerOptions"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                align="right"
                @change="hilltimechange"
              >
              </el-date-picker>
            </el-col>
            <el-button @click="hilldataDownload">导出数据</el-button>
          </el-row>
          <!-- 山体数据 -->
          <el-table
            stripe
            id="out-table"
            :data="hillData"
            border
            style="width: 100%"
            align="center"
          >
            <el-table-column type="index"></el-table-column>
            <el-table-column
              prop="createdTime"
              label="时间"
              width="140px"
            ></el-table-column>
            <el-table-column
              prop="totalInjectionVolume"
              label="总注液量 L"
            ></el-table-column>
            <el-table-column
              prop="airTemperature"
              label="空气温度 ℃"
            ></el-table-column>
            <el-table-column
              prop="airHumidity"
              label="空气湿度 %"
            ></el-table-column>
            <el-table-column
              prop="soilTemperature"
              label="土壤温度 ℃"
            ></el-table-column>
            <el-table-column
              prop="soilHumidity"
              label="土壤湿度 %"
            ></el-table-column>
            <el-table-column prop="rainfull" label="雨量 mm"></el-table-column>
          </el-table>
          <!-- 分页区域 -->
          <el-pagination
            v-show="hillShow"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="queryInfo.pagenum"
            :total="queryInfo.total"
            :page-sizes="[1, 2, 5, 10]"
            :page-size="queryInfo.pagesize"
            layout="total, sizes, prev, pager, next, jumper"
          >
          </el-pagination>
        </el-card>

        <!-- 注液管数据展示 -->
      </el-tab-pane>
      <el-tab-pane label="注液管数据" name="second"  v-loading="loading1">
        <el-card>
          <el-row :gutter="20">
            <el-col :span="10">
              <!-- 搜索与添加区域 -->
              <el-input
                placeholder="请输入内容"
                v-model="queryInfo.query"
                clearable
              >
                <el-button
                  slot="append"
                  icon="el-icon-search"
                ></el-button>
              </el-input>
            </el-col>
            <!-- 选择时间范围 -->
            <el-col :span="10">
              <el-date-picker
                v-model="tubetime"
                type="datetimerange"
                value-format="yyyy-MM-dd HH:mm:ss"
                :picker-options="pickerOptions"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                align="right"
                @change="tubetimechange"
              >
              </el-date-picker>
            </el-col>
            <el-button @click="tubedataDownload">导出数据</el-button>
          </el-row>
          <el-table stripe :data="tubeData" border style="width: 100%">
            <el-table-column type="index"></el-table-column>
            <el-table-column
              prop="createdTime"
              label="时间"
              width="140px"
            ></el-table-column>
            <el-table-column
              prop="pipeId"
              label="注液管号"
              width="100px"
            ></el-table-column>
            <el-table-column prop="angle" label="倾斜角"></el-table-column>
            <el-table-column
              prop="liquidLevel"
              label="液面高度"
            ></el-table-column>
            <el-table-column
              prop="injectionVolume"
              label="注液量"
            ></el-table-column>
            <el-table-column
              prop="valveStatus"
              label="阀门状态"
            ></el-table-column>
          </el-table>
          <!-- 分页区域 -->
          <el-pagination
            v-show="tubeShow"
            @size-change="tubehandleSizeChange"
            @current-change="tubehandleCurrentChange"
            :current-page="queryInfo.tubepagenum"
            :total="queryInfo.tubetotal"
            :page-sizes="[5, 10]"
            :page-size="queryInfo.tubepagesize"
            layout="total, sizes, prev, pager, next, jumper">
          </el-pagination>
        </el-card>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>
<script>
import { listMountainData ,listMountainDataByTime,listPipeData,listPipeDataByTime} from "@/api/system/history";
import XLSX from "xlsx";
import FileSaver from "file-saver";
export default {
  name: "History",
  data() {
    return {
      // 下载链接
      ashow: false,
      // 下载地址
      url: '',
      // 文件名
      filename: '',
      // 数据库导出的按钮
      dialogVisible: false,
      // 分页的展示
      hillShow: true,
      tubeShow: true,
      // 加载
      dialog: false,
      loading1: false,
      loading: false,
      // 默认选中用户审核
      activeName: "first",
      // 获取用户列表的参数对象
      queryInfo: {
        total: 0,
        tubetotal: 0,
        // 搜索值
        query: '',
        // 当前的页数
        pagenum: 1,
        // 当前每次显示多少条数据
        pagesize: 5,
        // 当前的页数
        tubepagenum: 1,
        // 当前每次显示多少条数据
        tubepagesize: 5,
      },
      // 山体数据
      hillData: [],
      // 注液管数据
      tubeData: [],
      pickerOptions: {
        shortcuts: [
          {
            text: "最近一周",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit("pick", [start, end]);
            }
          },
          {
            text: "最近一个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit("pick", [start, end]);
            }
          },
          {
            text: "最近三个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit("pick", [start, end]);
            }
          }
        ]
      },
      time: "",
      tubetime: ""
    }
  },
  created() {
    this.gethillList();
    this.gettubeList();
  },
  methods: {
    // 数据库导出的按钮
     async outdatabase() {
      // this.ashow = true
      // const params = {
      //   fileName: this.filename
      // }
      // console.log('params',params)
      // const { data: res } = await this.$http.post('/dataManage/dbBackup?' + 'fileName=' + params.fileName)
      // this.url = 'http://42.194.128.233:8080/common/download?' + 'fileName=' + res.msg
      // console.log('下载地址', this.url)
    },
    // 山体数据时间范围发生变化
     async hilltimechange() {
      const params = {
        current: 1,
        size: 100000,
        startTime: this.time[0],
        endTime: this.time[1]
      }
      console.log('params',params)
      //const { data: res } = await this.$http.post('/dataCenter/queryMountainDataByTime',params)
       listMountainDataByTime(params).then(res=>{
       console.log('获取的数据是', res)
       this.hillData = res.data.list
       this.tubepagenum = params.current
       this.tubepagesize = params.size
       this.hillShow = flase
       console.log('分页展示', this.hillShow)
       })
    },
    // 获取山体的信息
    async gethillList() {
      const params = {
        current: this.queryInfo.pagenum,
        size: this.queryInfo.pagesize
      }
      listMountainData(params).then(response => {
        this.hillData = response.data.list
        this.queryInfo.total = response.data.total
        this.loading = false
        this.hillShow = true
      })
    },
    // 注液管数据时间范围发生变化
     async tubetimechange() {
      const params = {
        current: 1,
        size: 100000,
        startTime: this.tubetime[0],
        endTime: this.tubetime[1]
      }
      console.log('注液管时间查询传参',params)
      //const { data: res } = await this.$http.post('/dataCenter/queryPipeDataByTime',params)
      listPipeDataByTime(params).then(res=>{
        console.log("rrrrrrrrrrrrrrrr",res);
      console.log('时间搜索注液管信息', res)
       for (var i = 0; i < res.data.list.length; i++){
        if(res.data.list[i] === 1){
          res.data.list[i].valveStatus = '开'
        } else {
          res.data.list[i].valveStatus = '关'
        }
       }
       this.tubeData = res.data.list
       this.tubeShow = flase
      })
    },
    // 获取注液管信息
    async gettubeList() {
      const params = {
        current: this.queryInfo.tubepagenum,
        size: this.queryInfo.tubepagesize
      }
      console.log('注液管的params', params)
      //const { data: res } = await this.$http.get("/dataCenter/queryAllPipeData?" + 'current=' + params.current + '&size=' + params.size)
      listPipeData(params).then(res=>{
      console.log("注液管", res)
      for (var i = 0; i < res.data.list.length; i++){
        if(res.data.list[i] === 1){
          res.data.list[i].valveStatus = '开'
        } else {
          res.data.list[i].valveStatus = '关'
        }
      }
      this.tubeData = res.data.list
      this.loading1 = false
      this.tubeShow = true
      this.queryInfo.tubetotal = res.data.total
      console.log("注液管", this.tubeData)
      })

    },
    tubedataDownload() {
      console.log(4654651)
      this.excelData = this.tubeData; //将你要导出的数组数据（tubeData）赋值给excelDate
      this.exportExcel(); //调用export2Excel函数，填写表头（clomns里的type）和对应字段(historyList里的属性名)
    },
    //表格数据写入excel
    exportExcel() {
      var that = this;
      require.ensure([], () => {
        const { export_json_to_excel } = require("@/vendor/Export2Excel.js");
        //这里使用绝对路径( @表示src文件夹 )，使用@/+存放export2Excel的路径【也可以写成相对于你当前"xxx.vue"文件的相对路径，例如我的页面放在assets文件夹同级下的views文件夹下的“home.vue”里，那这里路径也可以写成"../assets/excel/Export2Excel"】
        const tHeader = [
          "时间",
          "注液管号",
          "倾斜角",
          "液面高度",
          "注液量",
          "阀门状态"
        ]; // 导出的excel表头名信息
        const filterVal = [
          "createdTime",
          "pipeId",
          "angle",
          "liquidLevel",
          "injectionVolume",
          "valveStatus"
        ]; // 导出的excel表头字段名，需要导出表格字段名
        const list = that.excelData;
        const data = that.formatJson(filterVal, list);
        export_json_to_excel(tHeader, data, "注液管历史数据"); // 导出的表格名称，根据需要自己命名
      });
    },
    hilldataDownload() {
      this.excelData = this.hillData; //将你要导出的数组数据（hillData）赋值给excelDate
      this.export2Excel(); //调用export2Excel函数，填写表头（clomns里的type）和对应字段(historyList里的属性名)
    },
    //表格数据写入excel
    export2Excel() {
      var that = this;
      require.ensure([], () => {
        const { export_json_to_excel } = require("@/vendor/Export2Excel.js");
        //这里使用绝对路径( @表示src文件夹 )，使用@/+存放export2Excel的路径【也可以写成相对于你当前"xxx.vue"文件的相对路径，例如我的页面放在assets文件夹同级下的views文件夹下的“home.vue”里，那这里路径也可以写成"../assets/excel/Export2Excel"】
        const tHeader = [
          "时间",
          "总注液量",
          "空气温度",
          "空气湿度",
          "土壤温度",
          "土壤湿度",
          "雨量"
        ]; // 导出的excel表头名信息
        const filterVal = [
          "createdTime",
          "totalInjectionVolume",
          "airHumidity",
          "airTemperature",
          "soilTemperature",
          "soilHumidity",
          "rainfull"
        ]; // 导出的excel表头字段名，需要导出表格字段名
        const list = that.excelData;
        const data = that.formatJson(filterVal, list);
        export_json_to_excel(tHeader, data, "山体历史数据"); // 导出的表格名称，根据需要自己命名
      });
    },
    //格式转换，直接复制即可,不需要修改什么
    formatJson(filterVal, jsonData) {
      return jsonData.map(v => filterVal.map(j => v[j]));
    },
    // 监听 pagesize 改变的事件
    handleSizeChange (newSzie) {
      console.log(newSzie)
      this.queryInfo.pagesize = newSzie
      this.queryInfo.pagenum = 1
      this.gethillList()
    },
    // 监听 页码值 改变的事件
    handleCurrentChange (newPage) {
      this.queryInfo.pagenum = newPage
      this.gethillList()
    },
    // 注液管监听 pagesize 改变的事件
    tubehandleSizeChange (newSzie) {
      console.log(newSzie)
      this.queryInfo.tubepagesize = newSzie
      this.queryInfo.tubepagenum = 1
      this.gettubeList()
    },
    // 注液管监听 页码值 改变的事件
    tubehandleCurrentChange (newPage) {
      this.queryInfo.tubepagenum = newPage
      this.gettubeList()
    }
  }
};
</script>

<style scoped lang='scss'>
.el-col-5 {
    width: 20.83333%;
    margin-top: 10px;
}
// 数据库导出按钮样式
.database {
  z-index: 999;
  height: 40px;
  box-sizing: border-box;
  line-height: 34px;
  font-size: 20px;
  font-weight: 500;
  color: #e0c8d1;
  position: relative;
  left: 220px;
  top: -2px;
}
.el-tabs__header {
  padding: 0;
  position: relative;
  margin: -30px 0 7px;
}
// 山体数据和注液管数据样式
.el-tabs__item {
  padding: 0 10px;
  height: 40px;
  box-sizing: border-box;
  line-height: 34px;
  display: inline-block;
  list-style: none;
  font-size: 20px;
  font-weight: 500;
  color: #e0c8d1;
  position: relative;
}
.el-tabs__nav-wrap::after {
  content: "";
  position: absolute;
  left: 0;
  bottom: 0;
  width: 0%;
  height: 1px;
  background-color: none;
  z-index: 1;
}
// 设置内边距
.history {
  padding: 0 20px 30px 20px;
}
// 设置table的样式
.el-table {
  margin-top: 10px;
  font-size: 12px;
}
.el-pagination {
  margin-top: 10px;
  font-size: 12px;
}
a {
  margin-left: 10px;
}
</style>
